package hr.web.filter;

import java.io.IOException;
import java.util.Date;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

public class ExpiresFilter implements Filter {

	private static final long DEFAULT_TIME = 3600L;
	// private static final String EXPIRES = "expires";
	private long expiresTime;
	private FilterConfig config;
	private static boolean no_init = true;

	public ExpiresFilter() {
	}

	public void init(final FilterConfig filterconfig) throws ServletException {
		config = filterconfig;
		no_init = false;
		final String s = filterconfig.getInitParameter("expires");
		if (s != null) {
			try {
				expiresTime = Long.parseLong(s);
			} catch (final Exception exception) {
				expiresTime = DEFAULT_TIME;
			}
		} else {
			expiresTime = DEFAULT_TIME;
		}
	}

	public FilterConfig getFilterConfig() {
		return config;
	}

	public void setFilterConfig(final FilterConfig filterconfig) {
		if (no_init) {
			no_init = false;
			config = filterconfig;
			final String s = filterconfig.getInitParameter("expires");
			if (s != null) {
				try {
					expiresTime = Long.parseLong(s);
				} catch (final Exception exception) {
					expiresTime = 3600L;
				}
			} else {
				expiresTime = 3600L;
			}
		}
	}

	public void doFilter(final ServletRequest servletrequest,
			final ServletResponse servletresponse, final FilterChain filterchain)
			throws ServletException, IOException {
		final HttpServletResponse httpservletresponse = (HttpServletResponse) servletresponse;
		final Date date = new Date();
		httpservletresponse.setDateHeader("Expires", date.getTime()
				+ expiresTime * 1000L);
		httpservletresponse.setHeader("Cache-Control", new StringBuilder()
				.append("max-age=").append(expiresTime).toString());

		filterchain.doFilter(servletrequest, servletresponse);
	}

	public void destroy() {
		config = null;
	}

}